package com.qsw.paper.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qsw.paper.constant.JwtClaimsConstant;
import com.qsw.paper.constant.MessageConstants;
import com.qsw.paper.constant.StatusConstants;
import com.qsw.paper.exception.ObjectException;
import com.qsw.paper.mapper.ThesesMapper;
import com.qsw.paper.mapper.UsersMapper;
import com.qsw.paper.pojo.dto.StudentsDto;
import com.qsw.paper.pojo.dto.StudentsQueryDto;
import com.qsw.paper.pojo.entity.Students;
import com.qsw.paper.mapper.StudentsMapper;
import com.qsw.paper.pojo.entity.Theses;
import com.qsw.paper.pojo.entity.Users;
import com.qsw.paper.pojo.vo.StudentCountByYearVO;
import com.qsw.paper.pojo.vo.StudentPageVO;
import com.qsw.paper.pojo.vo.StudentsVO;
import com.qsw.paper.result.PageResult;
import com.qsw.paper.service.IStudentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author qsw
 * @since 2024-11-15
 */
@Service
@RequiredArgsConstructor
public class StudentsServiceImpl extends ServiceImpl<StudentsMapper, Students> implements IStudentsService {

    private final UsersMapper usersMapper;
    private final ThesesMapper thesesMapper;

    /**
     * 分页查询学生
     *
     * @param queryDto dto
     * @return 分页数据
     */
    @Override
    public PageResult<?> pageList(@NotNull StudentsQueryDto queryDto) {
        Page<StudentPageVO> studentsPage = baseMapper
                .selectPageList(new Page<>(queryDto.getPageNum(), queryDto.getPageSize()), queryDto);
        return new PageResult<>(studentsPage.getTotal(), studentsPage.getRecords());
    }

    /**
     * 添加学生
     */
    @Transactional
    @Override
    public void save(StudentsDto studentsDto) {
        Users users = BeanUtil.copyProperties(studentsDto, Users.class)
                .setCreatedAt(LocalDateTime.now())
                .setStatus(StatusConstants.ONE)
                .setRole(StatusConstants.ONE)
                .setPassword(DigestUtils.md5DigestAsHex(JwtClaimsConstant.INITIAL_PASSWORD.getBytes()));

        usersMapper.insert(users);

        baseMapper.insert(BeanUtil.copyProperties(studentsDto, Students.class)
                .setCreatedAt(LocalDateTime.now())
                .setUserId(users.getUserId()));
    }

    /**
     * 修改学生信息
     *
     * @param id          学生id
     * @param studentsDto dto
     */
    @Transactional
    @Override
    public void update(@NotNull StudentsDto studentsDto, Integer id) {

        Integer userId = studentsDto.getUserId();

        // 查询当前用户数据
        Users currentUser = usersMapper.selectById(userId);
        if (currentUser == null) {
            throw new ObjectException("用户不存在");
        }

        // 获取前端传递的数据并去除空格
        String newEmail = StringUtils.trimToNull(studentsDto.getEmail());
        String newPhone = StringUtils.trimToNull(studentsDto.getPhone());
        String newAvatar = StringUtils.trimToNull(studentsDto.getAvatar());

        // 创建动态更新语句
        LambdaUpdateWrapper<Users> updateWrapper = new LambdaUpdateWrapper<>();
        boolean needUpdate = false;

        // 检查新值与当前值是否不同，值不同才更新
        if (newEmail != null && !newEmail.equals(currentUser.getEmail())) {
            updateWrapper.set(Users::getEmail, newEmail);
            needUpdate = true;
        }
        if (newPhone != null && !newPhone.equals(currentUser.getPhone())) {
            updateWrapper.set(Users::getPhone, newPhone);
            needUpdate = true;
        }
        if (newAvatar != null && !newAvatar.equals(currentUser.getAvatar())) {
            updateWrapper.set(Users::getAvatar, newAvatar);
            needUpdate = true;
        }

        // 如果有需要更新的字段，执行更新操作
        if (needUpdate) {
            updateWrapper.eq(Users::getUserId, userId); // 更新条件
            usersMapper.update(null, updateWrapper);
        }
        updateById(BeanUtil.copyProperties(studentsDto, Students.class).setStudentId(id));
    }

    /**
     * 删除学生
     *
     * @param id 学生id
     */
    @Transactional
    @Override
    public void delete(Integer id) {
        Students students = getById(id);
        if (students == null) {
            throw new ObjectException(MessageConstants.STUDENT_NULL);
        }
        Theses theses = thesesMapper.selectOne(new LambdaQueryWrapper<Theses>().eq(Theses::getStudentId, id));
        if (theses != null) {
            throw new ObjectException(MessageConstants.THESE_ERR);
        }
        baseMapper.deleteById(id);
        usersMapper.deleteById(students.getUserId());
    }

    /**
     * 获取学生详细信息
     *
     * @param id 学生id
     * @return 学生实体
     */
    @Override
    public StudentsVO findById(Integer id) {
        return baseMapper.findByStudentId(id);
    }

    /**
     * 按年份展示每个学年学校的所有学生人数（近五年）
     *
     * @return 数据列表
     */
    @Override
    public List<StudentCountByYearVO> getStudentCountByYear() {
        return baseMapper.getStudentCountByYear();
    }
}
